package club.ruanx.movie.controller;

import club.ruanx.acl.entity.SysUser;
import club.ruanx.acl.service.SysUserService;
import club.ruanx.bean.PageBean;
import club.ruanx.bean.ResultVO;
import club.ruanx.core.exception.TargetEntityNotFound;
import club.ruanx.movie.common.aop.annotation.FilterSensitiveCommentWords;
import club.ruanx.movie.controller.vo.NewsCommentVO;
import club.ruanx.movie.param.NewsCommentParam;
import club.ruanx.movie.service.NewsCommentService;
import club.ruanx.security.bean.UserAuthInfoContextHolder;
import club.ruanx.util.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 阮胜
 * @date 2018/11/11 20:35
 */
@RestController
@RequestMapping("/news/comment")
public class NewsCommentController {
    private final NewsCommentService newsCommentService;
    private final SysUserService sysUserService;

    public NewsCommentController(NewsCommentService newsCommentService, SysUserService sysUserService) {
        this.newsCommentService = newsCommentService;
        this.sysUserService = sysUserService;
    }

    @PostMapping("/submit")
    @PreAuthorize("hasAnyRole('USER')")
    @FilterSensitiveCommentWords(key = "#newsCommentParam.content")
    public ResultVO submit(@RequestBody @Valid NewsCommentParam newsCommentParam) throws Exception {
        String uid = UserAuthInfoContextHolder.getCurrentUserAuthInfoThrow().getUid();
        newsCommentParam.setUserId(uid);
        newsCommentService.saveParam(newsCommentParam);
        return ResultVO.builder().success(true).message("评论成功").build();
    }

    @GetMapping("/{id}/list")
    public List<NewsCommentVO> comments(@PathVariable String id, PageBean pageBean) {
        return newsCommentService.findAllByNewsId(id, pageBean).getContent().stream()
                .map(newsComment -> {
                    NewsCommentVO newsCommentVO = new NewsCommentVO();
                    BeanUtils.copyPropertiesIgnoreNull(newsComment, newsCommentVO);
                    try {
                        SysUser user = sysUserService.findById(newsComment.getUserId());
                        newsCommentVO.setUser(user);
                    } catch (TargetEntityNotFound targetEntityNotFound) {
                        targetEntityNotFound.printStackTrace();
                    }
                    return newsCommentVO;
                }).collect(Collectors.toList());
    }

}
